package com.chen.palmar.project.producer;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.BannerImageLoader;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.ShareDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.CollectEntity;
import com.chen.palmar.entity.StoreDetailEntity;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.exception.ApiException;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * Created by chen on 2018/1/4.
 */

public class StoreDetailActivity extends BaseActivity {

    @Bind(R.id.rb_store_base)
    RadioButton rbStoreBase;
    @Bind(R.id.rb_store_detail)
    RadioButton rbStoreDetail;
    @Bind(R.id.rg_store_state)
    RadioGroup rgStoreState;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.banner_view)
    Banner bannerView;
    @Bind(R.id.tv_store_detail_name)
    TextView tvStoreDetailName;
    @Bind(R.id.tv_store_detail_share)
    TextView tvStoreDetailShare;
    @Bind(R.id.tv_store_detail_price)
    TextView tvStoreDetailPrice;
    @Bind(R.id.tv_store_detail_location)
    TextView tvStoreDetailLocation;
    @Bind(R.id.tv_store_detail_watch)
    TextView tvStoreDetailWatch;
    @Bind(R.id.tv_store_detail_brand)
    TextView tvStoreDetailBrand;
    @Bind(R.id.tv_store_detail_info)
    TextView tvStoreDetailInfo;
    @Bind(R.id.textView2)
    TextView textView2;
    @Bind(R.id.tv_store_detail_out)
    TextView tvStoreDetailOut;
    @Bind(R.id.tv_store_detail_qz)
    TextView tvStoreDetailQz;
    @Bind(R.id.tv_store_detail_date)
    TextView tvStoreDetailDate;
    @Bind(R.id.tv_store_detail_code)
    TextView tvStoreDetailCode;
    @Bind(R.id.tv_store_detail_licence)
    TextView tvStoreDetailLicence;
    @Bind(R.id.rv_detail_comment)
    RecyclerView rvDetailComment;
    @Bind(R.id.tv_detail_collection)
    TextView tvDetailCollection;
    @Bind(R.id.tv_detail_contact)
    TextView tvDetailContact;
    private List<Object> images = new ArrayList<>();
    private BaseQuickAdapter<StoreDetailEntity.DataBean.CommentsBean, BaseViewHolder> adapterComment;
    private StoreDetailEntity.DataBean data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_store_detail;
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> StoreDetailActivity.this.finish());

        //设置指示器位置（当banner模式中有指示器时）
        bannerView.setIndicatorGravity(BannerConfig.CENTER);
        bannerView.setImageLoader(new BannerImageLoader());

        //        rgStoreState.setOnCheckedChangeListener((group, checkedId) -> {
        //            switch (checkedId) {
        //                case R.id.rb_store_base:
        //                    rbStoreBase.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        //                    rbStoreDetail.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        //                    break;
        //                case R.id.rb_store_detail:
        //                    rbStoreDetail.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        //                    rbStoreBase.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        //                    break;
        //            }
        //        });

        rvDetailComment.setNestedScrollingEnabled(false);
        LinearLayoutManager layoutManagerComment = new LinearLayoutManager(StoreDetailActivity.this);
        layoutManagerComment.setOrientation(LinearLayoutManager.VERTICAL);
        rvDetailComment.setLayoutManager(layoutManagerComment);
        adapterComment = new BaseQuickAdapter<StoreDetailEntity.DataBean.CommentsBean, BaseViewHolder>(R.layout.item_detail_comment) {
            @Override
            protected void convert(BaseViewHolder helper, StoreDetailEntity.DataBean.CommentsBean item) {
                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_comment_head);
                Picasso.with(StoreDetailActivity.this).load(item.getAvatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
                helper.setText(R.id.tv_item_comment_name, item.getName());
                helper.setText(R.id.tv_item_comment_date, item.getCreate_at());
                helper.setText(R.id.tv_item_comment_content, item.getContent());
            }
        };
        rvDetailComment.setItemAnimator(new DefaultItemAnimator());
        rvDetailComment.setAdapter(adapterComment);

        tvDetailCollection.setTag(false);

        try {
            getDataForWeb(getIntent().getStringExtra("info"));
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据出错，请稍后重试");
        }
    }

    private void getDataForWeb(String info) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("productId", info);
        Subscription subscribe = DataCenter.storeDetailInfo(map).subscribe(new HttpSubscriber<StoreDetailEntity>(this, showLoading()) {

            @Override
            public void onNext(StoreDetailEntity entity) {
                data = entity.getData();
                if (data == null) {
                    showToast("服务器返回数据为空");
                    return;
                }
                images.clear();
                images.addAll(data.getImg());
                bannerView.setImages(images);
                bannerView.start();

                tvStoreDetailName.setText(data.getTitle());
                tvStoreDetailPrice.setText(data.getGuidance_price());
                tvStoreDetailLocation.setText(data.getAddress_detail());
                tvStoreDetailBrand.setText(data.getBrand());
                tvStoreDetailInfo.setText(data.getSales_type());
                tvStoreDetailOut.setText(data.getIs_imported());
                tvStoreDetailQz.setText(data.getIs_muslim());
                tvStoreDetailLicence.setText(data.getLicence());
                tvStoreDetailDate.setText(data.getShelf_life());
                tvStoreDetailCode.setText(data.getCode());

                adapterComment.setNewData(data.getComments());

                if (data.getFavoriteStatus() == 1) {
                    tvDetailCollection.setTag(true);
                    Drawable select = ContextCompat.getDrawable(StoreDetailActivity.this, R.mipmap.info_collectioned_icon);
                    tvDetailCollection.setCompoundDrawablesWithIntrinsicBounds(null, select, null, null);
                }
            }
        });
        subscription.add(subscribe);
    }

    @OnClick({R.id.tv_detail_collection, R.id.tv_detail_contact, R.id.tv_store_detail_share})
    public void onViewClicked(View view) {
        if (data == null) {
            showToast("详情加载失败");
        }
        switch (view.getId()) {
            case R.id.tv_detail_collection:
                collectInfo(getIntent().getStringExtra("info"), ((boolean) tvDetailCollection.getTag()));
                break;
            case R.id.tv_detail_contact:
                contactStore(getIntent().getStringExtra("info"));
                break;
            case R.id.tv_store_detail_share:
                shareStore(getIntent().getStringExtra("info"));
                break;
        }
    }

    /**
     * 收藏
     *
     * @param tag
     */
    private void collectInfo(String info, boolean tag) {
        CommentRequest.collectInfo(info, "3", tag, new CommentRequest.OnLoadSuccessListener<CollectEntity>() {
            @Override
            public void onSuccess(CollectEntity entity) {
                if (!TextUtils.isEmpty(entity.getMessage())) {
                    showToast(entity.getMessage());
                    tvDetailCollection.setTag(!tag);
                    Drawable normal = ContextCompat.getDrawable(StoreDetailActivity.this, R.mipmap.info_collection_icon);
                    Drawable select = ContextCompat.getDrawable(StoreDetailActivity.this, R.mipmap.info_collectioned_icon);
                    tvDetailCollection.setCompoundDrawablesWithIntrinsicBounds(null, ((boolean) tvDetailCollection.getTag()) ? select : normal, null, null);
                }
            }

            @Override
            public void onFailure(ApiException e) {
                if ("已收藏，请勿重复收藏".equals(e.getMessage())) {
                    tvDetailCollection.setTag(!tag);
                    Drawable select = ContextCompat.getDrawable(StoreDetailActivity.this, R.mipmap.info_collectioned_icon);
                    tvDetailCollection.setCompoundDrawablesWithIntrinsicBounds(null, select, null, null);
                }
            }
        });
    }

    private void contactStore(String info) {
        HashMap<String, String> map = new HashMap<>();
        map.put("product_id", info);
        Subscription subscribe = DataCenter.contractSeller(map).subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading("正在询单")) {
            @Override
            public void onNext(HttpResultEntity httpResultEntity) {
                if (!TextUtils.isEmpty(httpResultEntity.getMessage())) {
                    showToast(httpResultEntity.getMessage());
                } else if (!TextUtils.isEmpty(httpResultEntity.getError())) {
                    showToast(httpResultEntity.getError());
                } else {
                    showToast("询单失败，具体原因请联系管理员");
                }
            }
        });
        subscription.add(subscribe);
    }

    private void shareStore(String info) {
        ShareDialog shareDialog = new ShareDialog();
        shareDialog.setRef_id(info);
        shareDialog.setRef_type("1");
        shareDialog.show(getSupportFragmentManager());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommentRequest.cancelRequest();
    }
}
